#pragma once

#pragma pack(push,1)
struct sPrivilegedIP
{
	DWORD	m_dwIPBegin;
	DWORD	m_dwIPEnd;
};
#pragma pack(pop)

class CPrivilegedIPManager
{
	inline DWORD ChangeByteOrder(DWORD data)
	{
		return ((data >> 24) & 0xFF) +
			(((data >> 16) & 0xFF) << 8) +
			(((data >> 8) & 0xFF) << 16) +
			((data & 0xFF) << 24);
	}

public:
	CPrivilegedIPManager()
	{

	}

	virtual ~CPrivilegedIPManager()
	{
		Release();
	}

	void	Release()
	{
		m_IPSet.clear();
	}

	void	AddIP(sPrivilegedIP* pIP, BOOL bBlockIP = FALSE)
	{
		DWORD dwIPBegin = ChangeByteOrder( pIP->m_dwIPBegin);
		DWORD dwIPEnd = ChangeByteOrder( pIP->m_dwIPEnd);

		for(DWORD dwIP = dwIPBegin; dwIP <= dwIPEnd; ++dwIP)
		{
			m_IPSet.insert( ChangeByteOrder( dwIP));
		}

		ReportLog( LOG_NOTIFY, _T("%s ip : %d.%d.%d.%d - %d.%d.%d.%d"), 
						((bBlockIP) ? _T("blocked") : _T("previleged") ),
						(dwIPBegin >> 24) & 0xFF, (dwIPBegin >> 16) & 0xFF, (dwIPBegin >> 8) & 0xFF, dwIPBegin & 0xFF,
						(dwIPEnd >> 24) & 0xFF, (dwIPEnd >> 16) & 0xFF, (dwIPEnd >> 8) & 0xFF, dwIPEnd & 0xFF);
	}

	BOOL	IsRegisteredIP(DWORD dwIP)
	{
		return m_IPSet.find( dwIP) != m_IPSet.end();
	}

	static void ConvertIP2String(DWORD dwIP, std::wstring& strIP)
	{
		WCHAR buf[256];
		if (SF_sprintf(buf, _countof(buf), _T("%d.%d.%d.%d"), (dwIP >> 0) & 0xFF, (dwIP >> 8) & 0xFF, (dwIP >> 16) & 0xFF, (dwIP >> 24) & 0xFF) != S_OK)
		{
			_ASSERT(FALSE);
		}
		strIP.assign(buf);
	}

protected:
	typedef stdext::hash_set<DWORD>	IPSET;
	IPSET		m_IPSet;
};
